var RockitJS = new Object();
RockitJS.Model = new Object();
RockitJS.Model.Database = new Object();

RockitJS.Model.Database.Abstract = function () {

    var $handle = null;
    var $this = this;

    /**
     * Create Database or open a connection to the database if it already exists
     *
     * @param string $shortName
     * @param string $version
     * @param string $displayName
     * @param string $maxSize
     *
     * @return object Database
     */
    this.connect = function($shortName, $version, $displayName, $maxSize)
    {
        if (typeof $shortName ==='undefined') {
            $shortName = window.location.hostname;
        }

        if (typeof $version ==='undefined') {
            $version = "1.0";
        }

        if (typeof $displayName ==='undefined') {
            $displayName = window.location.hostname;
        }

        if (typeof $maxSize ==='undefined') {
            $maxSize = 1048576; // in bytes
        }
        $maxSize = parseInt($maxSize);

        $handle = window.openDatabase($shortName, $version, $displayName, $maxSize);

        return $handle;
    };

    var _init = function($this)
    {
        try {
            if (!window.openDatabase) {
                alert("No DB support...");
                return false;
            } else {

                $this.connect();
            }
        } catch(e) {
            if (e == 0) {
                alert("Invalid database version.");
            } else {
                alert("Unknown error " + e);
            }
            return false;
        }
    };

    /**
     * Error handler
     *
     * @return void
     */
    var _errorHandler = function (transaction, error)
    {
      alert("Failure: " + error.message);;
    };

    // fire and forget...
    var _nullDataHandler = function (transaction, results)
    {

    };

    this.query = function($query, $callback)
    {
        try {
            $handle.transaction(
                function(transaction) {

                    transaction.executeSql(
                        $query,
                        [ ],
                        function (transaction, results) {
                            if ((typeof $callback) != "undefined") {
                                $callback(results);    
                            }
                        },
                        function (transaction, error) {
                            alert("Failure query: " + error.code + " Message: " + error.message);
                        }
                    );
                }
            );
        } catch(e) {
            alert("Unable to select data from the db " + e);
        }
    };

    // Initialize database
    _init(this);
};